package com.aloda.utils;

import com.aloda.properties.FileUploadProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 本地文件上传
 */
@Component
public class LocalUploadUtils {

    @Autowired
    private FileUploadProperties fileUploadProperties;

    // 保存上传的文件并返回文件的 URL
    public String saveFile(MultipartFile file) throws IOException {
        // 确保上传目录存在
        File uploadDir = new File(fileUploadProperties.getUploadPath());
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 获取当前时间戳并格式化
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
        String timestamp = now.format(formatter);

        // 生成一个唯一的文件名以避免冲突
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            throw new IllegalArgumentException("文件名错误");
        }
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = timestamp + "_" + UUID.randomUUID().toString() + fileExtension;
        Path filePath = Paths.get(fileUploadProperties.getUploadPath(), fileName);

        // 将文件保存到指定目录
        Files.write(filePath, file.getBytes());

        // 返回文件的 URL
        return fileUploadProperties.getAccessPath() + "/" + fileName;
    }
}
